package com.suxiaoxiao.springbootlearn.designpattern.commandpattern;

import com.suxiaoxiao.springbootlearn.designpattern.commandpattern.commands.Command;
import com.suxiaoxiao.springbootlearn.designpattern.commandpattern.commands.NoCommand;

/**
 * 控制器
 * @author 、
 */
public class RemoteControl {

    /**
     * 开启命令集
     */
    private Command[] onCommands;
    /**
     * 关闭命令集
     */
    private Command[] offCommands;
    /**
     * 前一个命令
     */
    private Command undoCommand;
    /**
     * 最大命令
     */
    private int maxCommand = 7;

    /**
     * 构造方法 初始化命令集
     */
    public RemoteControl() {
        onCommands = new Command[maxCommand];
        offCommands = new Command[maxCommand];

        // 空命令对象，防止空指针。
        Command noCommand = new NoCommand();
        for (int i = 0; i < maxCommand; i++) {
            onCommands[i] = noCommand;
            offCommands[i] = noCommand;
        }
        undoCommand = noCommand;
    }

    /**
     * 设置命令
     *
     * @param slot 命令集对应坐标
     * @param onCommand 开启命令
     * @param offCommand 关闭命令
     */
    public void setCommand(int slot, Command onCommand, Command offCommand) {
        onCommands[slot] = onCommand;
        offCommands[slot] = offCommand;
    }

    /**
     * 执行开启命令
     * @param slot 命令对应坐标
     */
    public void onButtonWasPushed(int slot) {
        onCommands[slot].execute();
        undoCommand = onCommands[slot];
    }

    /**
     * 执行关闭命令
     * @param slot 命令对应坐标
     */
    public void offButtonWasPushed(int slot) {
        offCommands[slot].execute();
        undoCommand = offCommands[slot];
    }

    /**
     * 执行撤销命令
     */
    public void undoButtonWasPushed() {
        undoCommand.undo();
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("\n ------ Remote Control ------ \n");
        for (int i = 0; i < onCommands.length; i++) {
            stringBuilder.append("[slot ").append(i).append(" ]")
                    .append(onCommands[i].getClass().getName())
                    .append("   ")
                    .append(offCommands[i].getClass().getName())
                    .append("\n");
        }
        return stringBuilder.toString();
    }
}
